package com.hainingtong.common.utils;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class Captcha {
    @Autowired
    DefaultKaptcha defaultKaptcha;

    @Autowired
    RedisUtils redisUtils;

    public boolean verify(String code) {
        if (!redisUtils.exists("captcha-" + code)) {
            return false;
        }
        redisUtils.remove("captcha-" + code);
        return true;
    }

    public Map<String, String> create() {

        Map<String, String> result = new HashMap<>();

        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到map中
            String createText = defaultKaptcha.createText();
            result.put("code", createText);

            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException | IOException e) {
            return null;
        }

        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

        String base64Str = "data:image/jpg;base64," + Base64.getEncoder().encodeToString(captchaChallengeAsJpeg);
        result.put("img", base64Str);

        // 把生成的值保存到redis
        redisUtils.set("captcha-" + result.get("code"), true, 1L, TimeUnit.MINUTES);

        return result;
    }

}
